package cn.sfa.controller.manage;

import java.awt.Rectangle;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.sfa.common.pagination.Pagination;
import cn.sfa.common.taglib.CommonCache;
import cn.sfa.common.utils.CommonUtil;
import cn.sfa.common.utils.FormValidate;
import cn.sfa.common.utils.ImageHepler;
import cn.sfa.common.utils.WebInitBinderContoller;
import cn.sfa.entity.affixItem.SaleAffixItem;
import cn.sfa.entity.agenthonour.SaleAgentHonour;
import cn.sfa.entity.system.BranchSysCode;
import cn.sfa.entity.team.TeamAgentInfoEntity;
import cn.sfa.entity.users.SaleUsersLogin;
import cn.sfa.service.affix.AffixService;
import cn.sfa.service.agentinfo.AgentInfoService;
import cn.sfa.service.login.LoginService;
import cn.sfa.service.promote.PromoteSerice;

@Controller
@RequestMapping("manage/agenter/index")
public class ManageAgenterController extends WebInitBinderContoller {

	Logger log = LoggerFactory.getLogger(ManageAgenterController.class);
	@Autowired
	LoginService loginService;
	
	@Autowired
	PromoteSerice promoteSerice;

	@Autowired
	private AffixService affixService;
	
	@Autowired
	private AgentInfoService agentInfoService;

	private String affixType = "USERPHOTO";

	// 判断是否是管理员
	public boolean isAdmin(HttpServletRequest request) {
		SaleUsersLogin saleUser = (SaleUsersLogin) request.getSession().getAttribute("user");
		if (saleUser.getUserType().equals("USERTYPE_3"))
			return true;
		return false;
	}

	/**
	 * 获取所有代理人
	 * 
	 * @author: LiXiang
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping("/getusers")
	public String getUers(
			@RequestParam(value = "agentName", required = false) String agentName,
			@RequestParam(value = "agentCode", required = false) String agentCode,
			@RequestParam(value = "branchid", required = false) String branchid,
			@RequestParam(value = "beginCreateDate", required = false) String beginCreateDate,
			@RequestParam(value = "endCreateDate", required = false) String endCreateDate,
			@RequestParam(value = "validFlag", required = false) String validFlag,
			HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		int currentPage = 1;
		if (agentName != null)
			agentName = agentName.trim();
		else agentName = "";
		if (agentCode != null)
			agentCode = agentCode.trim();
		else
			agentCode = "";
		if (branchid != null) {
			if ("BRA0000000000001".equals(branchid)) {
				branchid = "";
			}
			branchid = branchid.trim();
		} else
			branchid = "";
		if (!CommonUtil.isEmpty(request.getParameter("currentPage"))) {
			currentPage = Integer.parseInt(request.getParameter("currentPage"));
		}
		SaleUsersLogin user = (SaleUsersLogin) request.getSession()
				.getAttribute("user");
		String url = request.getContextPath() +
		"/manage/agenter/index/getusers?agentName="+agentName+
		"&agentCode="+agentCode+
		"&branchid="+branchid+
		"&beginCreateDate="+(CommonUtil.isEmpty(beginCreateDate)?"":beginCreateDate)+
		"&endCreateDate="+(CommonUtil.isEmpty(endCreateDate)?"":endCreateDate)+
		"&validFlag="+(CommonUtil.isEmpty(validFlag)?"":validFlag);
		Pagination pagination = agentInfoService.seachPromot(currentPage, 10, url,"BRA0000000000001",agentName,agentCode,branchid,beginCreateDate,endCreateDate,validFlag,0);
		
		map.put("pagination", pagination);
		map.put("agentName", agentName);
		map.put("agentCode", agentCode);
		map.put("branchid", branchid);
		List<BranchSysCode> list = null;
		map.put("BranchList", list);
		map.put("beginCreateDate", (CommonUtil.isEmpty(beginCreateDate)?"":beginCreateDate));
		map.put("endCreateDate", (CommonUtil.isEmpty(endCreateDate)?"":endCreateDate));
		map.put("validFlag", (CommonUtil.isEmpty(validFlag)?"":validFlag));
		return "manage/agenter/getusers";
	}
	
	
	
	/**
	 * 删除头像
	 * @throws IOException 
	 * 
	 * 
	 */
	@RequestMapping("/delete")
	public void delete( HttpServletRequest request,ModelMap map,HttpServletResponse response) throws IOException
	{
		String agentId = request.getParameter("agentId");
		List<SaleAffixItem> head=affixService.getAffix(affixType, agentId);
		SaleAffixItem s=null;
		for(SaleAffixItem affix:head)
		{
			if(affix.getIsTrue()!=null && affix.getIsTrue().equals("Y"))
			{
				affix.setIsTrue("N");
				s=affix;
				break;
			} 
		}
		boolean flag=affixService.update(s);
		
		
		response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        request.setCharacterEncoding("UTF-8");
 
            JSONObject temp = new JSONObject();
             
            temp.put("flag", flag);
             
            PrintWriter out=response.getWriter();
	        out.print(temp.toString());
			out.flush();
			out.close();
	}

	/**
	 * 修改
	 * 
	 * @author: LiXiang
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping("/editagentinfo")
	public String updateAgentInfo(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		String defaultPic = "/images/imageCut/man.GIF";
		String agentId = request.getParameter("agentId");
		String agentLogId = request.getParameter("agentLogId");
		SaleAgentHonour sa = agentInfoService.getAgentByAgentId(agentLogId);
		String affixMainId = "";
		String photo=defaultPic;//默认图片
		List<SaleAffixItem> head=affixService.getAffix(affixType, agentId);
		for(SaleAffixItem affix:head)
		{
			if(affix.getIsTrue()!=null && affix.getIsTrue().equals("Y"))
			{
				photo=affix.getSALEAFFIXITEMFILEPATH();
				affixMainId = affix.getSALEAFFIXITEMID();
				break;
			}
		}
		
		map.put("agentId", agentId);
		map.put("agentLogId", agentLogId);
		map.put("defaultPic", defaultPic);
		map.put("photo", photo);
		map.put("affixMainId", affixMainId);
		map.put("saleagenthonour", sa);
		return "manage/agenter/editagentinfo";
	}
	
	/**
	 * 新增
	 * 
	 * @author: LiXiang
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping("/newagentinfo")
	public String newAgentInfo(HttpServletRequest request,
			HttpServletResponse response, 
			ModelMap map) {
		String defaultPic = "/images/imageCut/man.GIF";
		String affixMainId = "";
		String photo=defaultPic;//默认图片
		String agentId = request.getParameter("agentId");
		String agentLogId = request.getParameter("agentLogId");
		String changeDate = request.getParameter("changeDate");
		
		List<SaleAffixItem> head=affixService.getAffix(affixType, agentId);
		for(SaleAffixItem affix:head)
		{
			if(affix.getIsTrue()!=null && affix.getIsTrue().equals("Y"))
			{
				photo=affix.getSALEAFFIXITEMFILEPATH();
				affixMainId = affix.getSALEAFFIXITEMID();
				break;
			}
		}
		
		map.put("agentId", agentId);
		map.put("agentLogId", agentLogId);
		map.put("defaultPic", defaultPic);
		map.put("photo", photo);
		map.put("affixMainId", affixMainId);
		map.put("changeDate", changeDate);	
		return "manage/agenter/newagentinfo";
	}
	
	
	/**
	 * 提交
	 * 
	 * @author: LiXiang
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping("/submitagentinfo")
	public String newAgentInfoSubmit(
			SaleAgentHonour saleAgentHonour,
			HttpServletRequest request, 
			HttpServletResponse response, 
			ModelMap map) {
		String defaultPic = "/images/imageCut/man.GIF";
		String agentId = request.getParameter("agentId");
		String agentLogId = request.getParameter("agentLogId");
		String changeDate = request.getParameter("changeDate");
		String type = request.getParameter("type");
		
		SaleUsersLogin user=(SaleUsersLogin)request.getSession().getAttribute("user");
		
		saleAgentHonour.setUpdateDate(new Date());
		saleAgentHonour.setUpdateUser(user.getUserName());
		saleAgentHonour.setAffixMainId(agentId);
		
		if ("new".equals(type)) {
			TeamAgentInfoEntity agent = agentInfoService.getAgentinfoByAgentId(agentId);
			
			saleAgentHonour.setAgentId(agentLogId);
			saleAgentHonour.setBranchId(agent.getBranchname());
			saleAgentHonour.setAgentCode(agent.getAgentlevel());
			saleAgentHonour.setAgentName(agent.getAgentname());
			saleAgentHonour.setCreateUser(user.getUserName());
			saleAgentHonour.setCreateDate(new Date());
			try {
				saleAgentHonour.setHonourDate((new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")).parse(changeDate));
			} catch (ParseException e) {
				saleAgentHonour.setHonourDate(null);
			}
			agentInfoService.saveAgentInfo(saleAgentHonour);
		} else if ("edit".equals(type)) {
			agentInfoService.updateAgentInfo(saleAgentHonour);
		}
		
		
		map.put("agentId", agentId);
		map.put("defaultPic", defaultPic);	
		return "redirect:/manage/agenter/index/getusers";
	}

	/**
	 * 管理头像
	 * 
	 * @author: LiXiang
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping("/updateImage")
	public String updateImage(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		String defaultPic = "/images/imageCut/man.GIF";
		String agentId = request.getParameter("agentId");
		List<SaleAffixItem> affixList = affixService.getAffix(affixType, agentId);
		for (SaleAffixItem agentAffix : affixList) {
			if ("Y".equals(agentAffix.getIsTrue())) {
				defaultPic = agentAffix.getSALEAFFIXITEMFILEPATH();
			}
		}

		map.put("defaultPic", defaultPic);
		map.put("agentId", agentId);
		map.put("step", 1);
		return "manage/agenter/uploadimage";
	}

	/**
	 * 上传头像
	 * 
	 * @author: LiXiang
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping("/upLoadImage")
	public String upLoadImage(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		// 应用程序的真实路径
		String path = request.getSession().getServletContext().getRealPath("/");
		String agentId = request.getParameter("agentId");
		String defaultPic = "/images/imageCut/man.GIF";
		int maxPostSize = 10 * 1024 * 1024;
		String message = affixService.uploadPicture(request, response, maxPostSize, affixType, path, agentId);

		if (message != null) {
			defaultPic = message;
		}
		map.put("defaultPic", defaultPic);
		map.put("picUrl", defaultPic);
		map.put("agentId", agentId);
		map.put("step", 2);
		return "manage/agenter/uploadimage";
	}

	/**
	 * 保存被剪切的头像
	 * 
	 * @author: LiXiang
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/saveCutImage")
	public @ResponseBody
	void saveCutImage(HttpServletRequest request, HttpServletResponse response, ModelMap map) throws IOException {
		String message = "";
		String defaultPic = "/images/imageCut/man.GIF";
		// 系统路径
		String path = request.getSession().getServletContext().getRealPath("/");
		int imageWidth = Integer.parseInt(request.getParameter("txt_width"));
		int imageHeight = Integer.parseInt(request.getParameter("txt_height"));
		int cutTop = Integer.parseInt(request.getParameter("txt_top"));
		int cutLeft = Integer.parseInt(request.getParameter("txt_left"));
		int dropWidth = Integer.parseInt(request.getParameter("txt_DropWidth"));
		int dropHeight = Integer.parseInt(request.getParameter("txt_DropHeight"));
		String agentId = request.getParameter("agentId");
		String picture = request.getParameter("picture");

		if (defaultPic.equals(picture)) {
			message = "n";
		}

		File file = new File((new StringBuilder(path)).append("/User").append(picture).toString());
		if (!file.exists()) {// 如果文件不存在,则创建目录
			file.mkdirs();
		}
		try {
			Rectangle rec = new Rectangle(cutLeft, cutTop, dropWidth, dropHeight);
			ImageHepler.cut(new File((new StringBuilder(path)).append(picture).toString()), file, imageWidth, imageHeight, rec);
		} catch (Exception e) {
			message = "n";
		}

		try {
			affixService.saveAffixPicture(request, response, affixType, agentId, "/User" + picture);
		} catch (Exception e) {
			message = "n";
		}
		response.setContentType("text/json");

		PrintWriter out = response.getWriter();
		JSONObject jo = new JSONObject();
		jo.put("result", message);
		jo.put("step", 3);
		jo.put("defaultPic", "/User" + picture);
		out.print(jo.toString());
		out.flush();
		out.close();
	}
	
	
	
	
	
	
	 
	@RequestMapping("/toUpdate")
	public String toUpdate(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		 
		return "manage/agenter/pwdPage";
	}
	
	
	@RequestMapping("/validate")
	public void validate(HttpServletRequest request, HttpServletResponse response, ModelMap map,
			@RequestParam(value="loginName", required=false) String loginName) throws IOException {
		
		PrintWriter out=response.getWriter();
		response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        request.setCharacterEncoding("UTF-8");         
         JSONObject temp = new JSONObject();
         log.info("loginName:::"+loginName);
		boolean isExists=loginService.isExists(loginName);
		String msg="";
		
		int count=0;
		if(isExists)
		{
			log.info("=============================================s错误 信息："+msg);
			SaleUsersLogin user=loginService.getUserByLoginName(loginName);
			if("USERTYPE_1".equals(user.getUserType()))
			{
				String userStatus=user.getUserStatus();
				List users=loginService.getUser(loginName);
			}else
			{
				msg="此用户并非代理人，不允许修改！";
				count+=1;
			}
		}
		else
		{
			msg="此用户不存在！";
			count+=1;
		}
		
		boolean result=count==0;
            temp.put("result",result);
            temp.put("msg", msg);
             
            
        out.print(temp.toString());
		out.flush();
		out.close();
	}
	
	
	
	@RequestMapping("/updatePwd")
	public void updatePwd(HttpServletRequest request, HttpServletResponse response, ModelMap map) throws IOException {
		 
		String loginname=request.getParameter("loginName");
		String pwd1=request.getParameter("pwd");
		String pwd2=request.getParameter("pwd2");
		
		PrintWriter out=response.getWriter();
		
		response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        request.setCharacterEncoding("UTF-8");         
         JSONObject temp = new JSONObject();
         
         
         
 		String msg="";
 		
 		int count=0;
 		
 		if(loginname==null || "".equals(loginname))
		{
			msg="用户名不能为空！";
			count=count+1;
		}else if(pwd1==null || "".equals(pwd1))
		{
			msg="密码不能为空！";
			count=count+1;
		}else if(pwd2==null || "".equals(pwd2))
		{
			msg="确认密码不能为空！";
			count=count+1;
		} else if(pwd1.length()<7 || pwd1.length()>14)
		{
			msg="密码长度必须在7到14位";
			count=count+1;
		}else if(!FormValidate.pwdStreng(pwd1))
		{
			msg= "密码必须包含数字，字母，特殊字符";
			count=count+1;
		}
		 else if(!pwd2.equals(pwd1))
		{
			msg="与密码不一致！";
			count=count+1;
		}else
		{
 		
	 		boolean isExists=loginService.isExists(loginname);
	 		if(isExists)
	 		{
	 			
	 			SaleUsersLogin user=loginService.getUserByLoginName(loginname);
	 			if("USERTYPE_1".equals(user.getUserType()))
	 			{
	 				String userStatus=user.getUserStatus();
	 				List users=loginService.getUser(loginname);
	 			}else
	 			{
	 				msg="此用户并非代理人，不允许修改！";
	 				count+=1;
	 			}
	 		}
	 		else
	 		{
	 			msg="此用户不存在！";
	 			count+=1;
	 		}
		
		
		}

		if(count==0)
		{
			if(isAdmin(request))
			{
			
			SaleUsersLogin saleUser=loginService.getUserByLoginName(loginname);
			SaleUsersLogin user=(SaleUsersLogin)request.getSession().getAttribute("user");
		}else
		{
			msg="对不起！你不是管理员，没有权限！";
		}
		
		}
		boolean result=count==0;
        temp.put("result",result);
        temp.put("msg", msg);
          
	    out.print(temp.toString());
		out.flush();
		out.close();
		
	}
	
}
